import {
		amapKey,
		securityJsCode,
	} from "@/uni_modules/jack-filepicker/common/config.js"
/**
 * 获取yyyy-MM-dd hh:mm:ss
 */
export function getNowDateTime(date = new Date()) {
	if (date) {
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		const seconds = date.getSeconds().toString().padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
}

/**
 * @param {Object} rpx
 * rpx==>px
 */
export function rpxTopx(rpx) {
	let deviceWidth = uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	let px = (deviceWidth / 750) * Number(rpx)
	return Math.floor(px);
}

/**
 * @param {Object} dataurl
 * base64转blob对象
 */
export function base64toBlob(dataurl) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}


/**
 * @param {Object} obj
 * blob生成临时url
 */
export function blobToUrl(obj) {
	return URL.createObjectURL(obj)
}
/**
 * @param {Object} canvas
 * 画布上是否有内容
 */
export function canvasHasContent(canvas, that) {
	return new Promise((reso, err) => {
		uni.canvasGetImageData(canvas, that).then(res => {
			const pixels = res.data;
			// 遍历像素数据，检查是否有不透明的像素
			for (let i = 0; i < pixels.length; i += 4) {
				if (pixels[i + 3] !== 0) { // 如果不是透明的，返回true
					reso(true)
				}
			}

			// 如果遍历完所有像素后都是透明的，返回false
			reso(false)
		})
	})
}

export async function urlImgRotate(url, deg, that) {
	let res = await uni.getImageInfo({
		src: url,
	})
	// #ifdef H5
	const img = document.createElement('img')
	img.src = url
	img.style.transform = `rotate(${deg}deg)`
	const canvas = document.createElement('canvas')
	if (deg % 180 == 0) {
		canvas.width = res.width
		canvas.height = res.height
	} else {
		canvas.width = res.height
		canvas.height = res.width
	}
	const context = canvas.getContext('2d')
	context.save()
	context.translate(canvas.width / 2, canvas.height / 2)
	context.rotate((deg % 360) * Math.PI / 180)

	if ((deg % 180) == 0) {
		context.translate(-canvas.width / 2, -canvas.height / 2)
	} else {
		context.translate(-canvas.height / 2, -canvas.width / 2)
	}
	context.drawImage(img, 0, 0)
	// let a = document.createElement('a')
	// a.href = canvas.toDataURL()
	// a.download = '23'
	// let e = new MouseEvent('click')
	// a.dispatchEvent(e)
	context.restore()
	// 获取画完后的数据
	return canvas.toDataURL('image/jpeg', 0.9)
	// #endif


	// #ifdef MP-WEIXIN
	let canvas = wx.createOffscreenCanvas({
		type: '2d',
		width: res.width,
		height: res.height,
	})
	let context = canvas.getContext('2d')
	// 创建一个图片
	let image = canvas.createImage()
	// 等待图片加载
	await new Promise((resolve, reject) => {
		image.src = url
		image.onload = () => {
			image.onload = null; // 清除事件监听器，防止重复触发
			resolve(image)
		}
		image.onerror = (error) => {
			reject(error)
		}
		// image.src = url + '?t=' + Date.now() //  尝试通过添加时间戳来绕过缓存,防止onload不触发
	})
	// 旋转画布
	context.save()
	context.translate(canvas.width / 2, canvas.height / 2)
	context.rotate((deg % 360) * Math.PI / 180)
	if ((deg % 180) == 0) {
		context.translate(-canvas.width / 2, -canvas.height / 2)
		// 把图片画到离屏 canvas 上
		context.drawImage(image, 0, 0, canvas.width, canvas.height)
	} else {
		context.translate(-canvas.height / 2, -canvas.width / 2)
		context.drawImage(image, 0, 0, canvas.height, canvas.width, )
	}
	context.restore()
	let re = await uni.canvasToTempFilePath({
		canvas: canvas
	})
	image.src = ''//清除小程序缓存的bug
	return re.tempFilePath
	// #endif
}
// 根据经纬度获取地址
export function getAddressByLngLat(data) {
	return new Promise((res, rej) => {
		if (data == null) {
			rej('位置获取失败，请确认是否开启定位')
		}
		uni.request({
			header: {
				"Content-Type": "application/text"
			},
			//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
			url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' + data.lng + ',' +
				data
				.lat + '&key='+amapKey+'c&radius=1000&extensions=all',
			success(re) {
				if (re.statusCode === 200) {
					let citydata = re.data.regeocode.formatted_address
					// console.log("获取中文街道地理位置成功", citydata)
					res(citydata)
				} else {
					uni.showToast({
						icon: 'none',
						title: '获取信息失败，，请确认是否开启定位'
					})
					rej('位置获取失败，请确认是否开启定位')
				}
			}
		});
	})

}

//获取经纬度
export function getLocation() {
	return new Promise((resove, rej) => {
		uni.showLoading({
			mask: true,
			title: '位置获取中'
		})
		uni.getLocation({
			type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			success: (res) => {
				const longs = res.longitude.toString();
				const lat = res.latitude.toString();
				if (longs !== '' && lat !== '') {
					uni.hideLoading()
					resove({
						lng: longs,
						lat: lat
					})
				}
			},
			fail: err => {
				uni.hideLoading()
				uni.showToast({
					title: '位置获取失败',
					icon: 'none',
				})
				rej(null)
			}
		});
	})

}